<!--
 * eslint-disable vue/no-mutating-props
-->
<template>
  <codemirror
    v-model="jscode"
    placeholder="js脚本"
    :style="{ height: '400px' }"
    :autofocus="true"
    :indent-with-tab="true"
    :tab-size="4"
    :extensions="extensions"
    @ready="handleReady"
    @change="emitFn"
    @focus="emitFn"
    @blur="emitFn"
  />
</template>
<script setup>
  import { defineComponent, ref, shallowRef, defineProps, watch, defineEmits } from 'vue';
  import { Codemirror } from 'vue-codemirror';
  import { javascript } from '@codemirror/lang-javascript';
  import { sql } from '@codemirror/lang-sql';

  import { oneDark } from '@codemirror/theme-one-dark';
  const props = defineProps({
    code: {
      type: String,
      default: '',
    },
    codeType: {
      type: String,
      default: 'js',
    },
  });
  const emits = defineEmits(['changecb']);
  const jscode = ref(null);
  const extensions = ref([]);
  const view = shallowRef();
  const handleReady = (payload) => {
    view.value = payload.view;
  };
  const emitFn = () => {
    emits('changecb', jscode.value);
  };
  // const getCodemirrorStates = () => {
  //   console.log('getCodemirrorStates');
  //   const state = view.value.state;
  //   const ranges = state.selection.ranges;
  //   const selected = ranges.reduce((r, range) => r + range.to - range.from, 0);
  //   const cursor = ranges[0].anchor;
  //   const length = state.doc.length;
  //   const lines = state.doc.lines;
  // };
  const log = console.log;
  watch(
    () => props,
    (nv) => {
      // console.log('🚀 ~ file: index.vue ~ line 60 ~ nv', nv);
      if (nv) {
        jscode.value = nv.code;
        switch (nv.codeType) {
          case 'js':
            extensions.value = [javascript(), oneDark];
            break;
          case 'sql':
            extensions.value = [sql(), oneDark];
            break;
        }
      }
    },
    {
      immediate: true,
    }
  );

  watch(
    () => props.code,
    (n) => {
      jscode.value = n;
    }
  );
</script>
